package com.junit;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.xpgk.config.ModelScan;
import com.xpgk.constant.ConstantInit;
import com.xpgk.dto.DataBase;
import com.xpgk.plugin.ServicePlugin;
import com.xpgk.plugin.SqlXmlPlugin;
import com.xpgk.tools.ToolBeetl;
import com.xpgk.tools.ToolDataBase;

/**
 * 独立启动JFinal中的插件，不依赖web容器调用插件
 * 
 */
public class ConfigCore {

	private static final Log log = Log.getLog(ConfigCore.class);

	private static volatile ConfigCore configCore;

	public static ConfigCore getSingleton() {
		if (configCore == null) {
			synchronized (ConfigCore.class) {
				if (configCore == null) {
					configCore = new ConfigCore();
				}
			}
		}
		return configCore;
	}

	private ConfigCore() {
		PropKit.use("init.properties");

		log.info("Beetl设置");
		ToolBeetl.regiseter();

		log.info("configPlugin 配置Druid数据库连接池连接属性");
		DataBase db = ToolDataBase.getDbMap(ConstantInit.db_dataSource_main);
		String db_type = db.getType();
		String driverClass = db.getDriverClass();
		String jdbcUrl = db.getJdbcUrl();
		String username = db.getUserName();
		String password = db.getPassWord();
		DruidPlugin druidPlugin = new DruidPlugin(jdbcUrl, username, password, driverClass);

		log.info("configPlugin 配置Druid数据库连接池大小");
		druidPlugin.set(db.getInitialSize(), db.getMinIdle(), db.getMaxActive());

		log.info("configPlugin 配置ActiveRecord插件");
		ActiveRecordPlugin arpMain = new ActiveRecordPlugin(ConstantInit.db_dataSource_main, druidPlugin);
		// arpMain.setTransactionLevel(4);//事务隔离级别
		boolean devMode = Boolean.parseBoolean(PropKit.get(ConstantInit.config_devMode));
		arpMain.setDevMode(devMode); // 设置开发模式
		arpMain.setShowSql(devMode); // 是否显示SQL
		arpMain.setContainerFactory(new CaseInsensitiveContainerFactory(true));// 大小写不敏感

		arpMain.setBaseSqlTemplatePath(PathKit.getRootClassPath()); // 设置sql文件存放的基础路径
		arpMain.addSqlTemplate("com/xpgk/mvc/user/User.sql"); // 添加sql模板

		log.info("configPlugin 使用数据库类型是 mysql");
		arpMain.setDialect(new MysqlDialect());

		ModelScan.scan(ConstantInit.db_dataSource_main, arpMain);
		druidPlugin.start();
		arpMain.start();

		log.info("ServicePlugin Service注解实例化加载");
		new ServicePlugin().start();

		log.info("EhCachePlugin EhCache缓存");
		new EhCachePlugin().start();

		log.info("SqlXmlPlugin 解析并缓存 xml sql");
		SqlXmlPlugin sqlXmlPlugin = new SqlXmlPlugin();
		sqlXmlPlugin.start();

		log.info("afterJFinalStart 缓存参数");
		// ParamInitPlugin paramInitPlugin = new ParamInitPlugin();
		// paramInitPlugin.start();
	}

}
